"""
@author: Sergiy Tsymbalyuk
"""

import os

from paste.script.command import Command, BadCommand
from paste.script.filemaker import FileOp

from tempita import paste_script_template_renderer

from pylons.util import class_name_from_module_name


class CreateCrudCommand(Command):
    summary = 'Create new CRUD Controller'
    group_name = 'chowa'
    parser = Command.standard_parser(verbose=False)
    def command(self):
        try:
            file_op = FileOp(source_dir=os.path.join(os.path.dirname(__file__), 'templates'))
            try:
                name, directory = file_op.parse_path_name_args(self.args[0])
            except:
                raise BadCommand("Sorry, can't parse given path")
            
            base_package = file_op.find_dir('controllers', True)[0]
            controller_name = class_name_from_module_name(name)
            model = raw_input('Model: ')
            file_op.template_vars.update({
                'model': model,
                'name': controller_name
            })
            file_op.copy_file(template='crud.py_tmpl',
                              dest=os.path.join('controllers', directory),
                              filename=name,
                              template_renderer=paste_script_template_renderer)
        except:
            BadCommand("Can't know what happened")
